package one.bugu.android.demon.ui.activity.snatch;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.text.SpannableString;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.juefeng.android.framework.LKUtil;
import com.juefeng.android.framework.common.util.ToastUtils;
import com.juefeng.android.framework.view.annotation.LKContentView;
import com.juefeng.android.framework.view.annotation.LKInjectView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import one.bugu.android.demon.R;
import one.bugu.android.demon.bean.snatch.SnatchPeriodBean;
import one.bugu.android.demon.common.BaseHttpAsycResponceHandler;
import one.bugu.android.demon.common.MyBaseActivity;
import one.bugu.android.demon.constant.Constant;
import one.bugu.android.demon.constant.HttpConstant;
import one.bugu.android.demon.constant.ShareConfig;
import one.bugu.android.demon.ui.activity.WebActivity;
import one.bugu.android.demon.ui.dialog.CustomDialog;
import one.bugu.android.demon.ui.refresh.SmartRefreshLayout;
import one.bugu.android.demon.ui.refresh.listener.OnRefreshListener;
import one.bugu.android.demon.ui.refresh.listener.RefreshLayout;
import one.bugu.android.demon.ui.widget.BaseTopBarView;
import one.bugu.android.demon.ui.widget.SelectPopupWindow;
import one.bugu.android.demon.ui.widget.XWebView;
import one.bugu.android.demon.util.IntentUtils;
import one.bugu.android.demon.util.MyTextUtils;
import one.bugu.android.demon.util.OnViewClickListener;
import one.bugu.android.demon.util.ParamUtils;
import one.bugu.android.demon.util.PreferencesUtil;
import one.bugu.android.demon.util.ShareDialogUtils;
import one.bugu.android.demon.util.ShareImageUtils;
import one.bugu.android.demon.util.ShareUtils;
import one.bugu.android.demon.util.StatusBarUtils;

/**
 * Description SnatchDetailsActivty 夺宝详情页面
 *
 * @author liuxin
 * @date 2018/10/27 15:13
 */
@LKContentView(R.layout.activity_snatch_details)
public class SnatchDetailsActivty extends MyBaseActivity {

    @LKInjectView(R.id.btbv_snatch_details)
    private BaseTopBarView btbv_snatch_details;

    @LKInjectView(R.id.tv_snatch_details_btn)
    private TextView tv_snatch_details_btn;

    @LKInjectView(R.id.progress_bar_web)
    private ProgressBar progressBar;

    @LKInjectView(R.id.xweb_web)
    private XWebView webView;

    @LKInjectView(R.id.ref_layout)
    private SmartRefreshLayout ref_layout;
    /**
     * 数据源
     */
    private SnatchPeriodBean.DataBean snatchData;

    private String token;
    private SelectPopupWindow popupWindow;
    private final int MAX_PROGESS = 100;

    private String mOrderNo = null;

    private int chooseCount = 0;

    private int chooseExpend = 0;

    @SuppressLint({"JavascriptInterface", "AddJavascriptInterface"})
    @Override
    protected void initView() {
        super.initView();

        StatusBarUtils.getInstance().setStatusBar("#FFFFFF", this, btbv_snatch_details, false);

        progressBar.setMax(MAX_PROGESS);
        progressBar.setVisibility(View.GONE);
        btbv_snatch_details.setRightBtnImageShow(false);

        webView.addJavascriptInterface(new WebOperation(), "android");
        ref_layout.setEnableLoadmore(false);
        ref_layout.setEnableRefresh(false);
    }

    @Override
    protected void initData() {
        super.initData();
        token = PreferencesUtil.getInstance().getString(this, Constant.TOKEN);

        Intent intent = getIntent();
        if (intent != null) {
            snatchData = (SnatchPeriodBean.DataBean) intent.getSerializableExtra("SNATCH_DATA");
        }
        //按钮显示
        setBottomBtnStatus(snatchData.getSTATUS());
        //H5地址
        String urls = HttpConstant.SNATCH_DETAILS_H5_URL;
        if (!TextUtils.isEmpty(urls) && snatchData != null) {
            urls = urls + "?token=" + token + "&status=" + snatchData.getSTATUS() + "&goodsId="
                    + snatchData.getGoodsId() + "&periodId=" + snatchData.getPeriodId() + "&appType=android";
            Log.d("initData", "initData: " + urls);
            webView.loadUrl(urls);
        }
        btbv_snatch_details.setTitle("第" + snatchData.getPeriodNo() + "期");
    }

    @Override
    protected void onResume() {
        super.onResume();
        webView.onResume();// 生命周期onResume
        //获取按钮
        setBottomBtnStatus(snatchData.getSTATUS());
    }

    @Override
    protected void onPause() {
        webView.onPause();
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        webView.destroy();
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
            // 返回前一个页面
            webView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        //topbar事件处理
        btbv_snatch_details.setEventInterface(new BaseTopBarView.EventInterface() {
            @Override
            public void leftOnClick() {
                finish();
            }

            @Override
            public void leftCloseClick() {

            }

            @Override
            public void rightOnClick() {
                //保存商品ID  用于在分享商品抢购时使用
                ShareUtils.saveGoodsId(SnatchDetailsActivty.this, snatchData.getGoodsId());
                //去分享
//                String inviteCode = PreferencesUtil.getInstance().getString(SnatchDetailsActivty.this, Constant.INVITE_CODE);
//                ShareDialogUtils.getInstance().shareUrl(SnatchDetailsActivty.this, HttpConstant.JOIN_H5_URL + inviteCode,
//                        ShareConfig.JOIN_TITLE, ShareConfig.JOIN_CONTENT, ShareConfig.JOIN_IMAGE, false);
                ShareImageUtils.getInstance().compShareWebImage(SnatchDetailsActivty.this, webView, btbv_snatch_details,false);
            }
        });
        //点击出现弹窗
        tv_snatch_details_btn.setOnClickListener(new OnViewClickListener() {
            @Override
            protected void singleClick(View view) {
                //立即抢购时显示弹窗
                if (snatchData == null || snatchData.getSTATUS() != 20) {
                    return;
                }
                String btnText = tv_snatch_details_btn.getText().toString().trim();
                if (ShareUtils.getShareStatus(SnatchDetailsActivty.this, snatchData.getGoodsId())
                        && TextUtils.equals(btnText, "立即抢购")) {
                    //已经分享过,直接去下单
                    popupWindow = new SelectPopupWindow(SnatchDetailsActivty.this, snatchData, new SelectPopupWindow.OnOrdersClickListener() {
                        @Override
                        public void ordersClick(int count, int expend, int periodId) {
                            SnatchDetailsActivty.this.chooseCount = count;
                            SnatchDetailsActivty.this.chooseExpend = expend;
                            placeOrder(count, periodId);
                        }
                    });
                    popupWindow.showPopupWindow();
                } else {
                    //保存商品ID  用于在分享商品抢购时使用
                    ShareUtils.saveGoodsId(SnatchDetailsActivty.this, snatchData.getGoodsId());
                    //去分享
//                    String inviteCode = PreferencesUtil.getInstance().getString(SnatchDetailsActivty.this, Constant.INVITE_CODE);
//                    ShareDialogUtils.getInstance().shareUrl(SnatchDetailsActivty.this, HttpConstant.JOIN_H5_URL + inviteCode,
//                            ShareConfig.JOIN_TITLE, ShareConfig.JOIN_CONTENT, ShareConfig.JOIN_IMAGE, false);
                    ShareImageUtils.getInstance().compShareWebImage(SnatchDetailsActivty.this, webView, btbv_snatch_details,false);
                }
            }
        });
        //web加载监听回调
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                setNewProgress(newProgress);
            }
        });

        //刷新
        ref_layout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                //调用JS方法去刷新界面
                webView.post(new Runnable() {
                    @Override
                    public void run() {
                        webView.loadUrl("javascript:reloadpage()");
                    }
                });
                ref_layout.finishRefresh();
            }
        });
    }

    /**
     * H5返回状态数据
     */
    private class WebOperation {

        @JavascriptInterface
        public void getSnatchStatus(String status) {
            try {
                int snatchStatus = Integer.parseInt(status);
                setBottomBtnStatus(snatchStatus);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 显示确认弹窗
     *
     * @param count  抢购份数
     * @param expend 共消耗BGT数量
     */
    private void showInfoConfirmDialog(final int count, int expend) {
        final CustomDialog infoConfirmDialog = new CustomDialog(this);
        infoConfirmDialog.setCancelBtnText("返回修改");
        infoConfirmDialog.setConfirmBtnText("确认抢购");
        View view = View.inflate(this, R.layout.dialog_info_confirm_layout, null);
        TextView tv_dialog_count = view.findViewById(R.id.tv_dialog_count);
        TextView tv_dialog_expend = view.findViewById(R.id.tv_dialog_expend);
        infoConfirmDialog.setTopView(view);
        SpannableString countText = MyTextUtils.getInstance().setAutoTextColor("抢购份数：" + count + "份", "[0-9]{1,}份", "#FF5453");
        tv_dialog_count.setText(countText);
        SpannableString expendText = MyTextUtils.getInstance().setAutoTextColor("本次消耗：" + expend + "BGT", "[0-9]{1,}[A-Z]{1,}", "#FF5453");
        tv_dialog_expend.setText(expendText);

        infoConfirmDialog.setEventInterface(new CustomDialog.EventInterface() {
            @Override
            public void cancelOnClick() {
                infoConfirmDialog.dismiss();
            }

            @Override
            public void confirmOnClick() {
                infoConfirmDialog.dismiss();
                payOrder(mOrderNo);
            }
        });
        infoConfirmDialog.show();
    }

    /**
     * 显示失败弹窗
     */
    private void showFailureDialog(String content, String cancelText, String confirmText) {
        final CustomDialog failureDialog = new CustomDialog(this);
        //取消按钮
        if (TextUtils.isEmpty(cancelText)) {
            failureDialog.visibleCancle();
        } else {
            failureDialog.setCancelBtnText(cancelText);
        }
        failureDialog.setConfirmBtnText(confirmText);
        View view = View.inflate(this, R.layout.dialog_failure_layout, null);
        TextView tv_dialog_content = view.findViewById(R.id.tv_dialog_content);
        tv_dialog_content.setText(content);
        failureDialog.setTopView(view);
        failureDialog.setEventInterface(new CustomDialog.EventInterface() {
            @Override
            public void cancelOnClick() {
                failureDialog.dismiss();
            }

            @Override
            public void confirmOnClick() {
                failureDialog.dismiss();
            }
        });
        failureDialog.show();
    }

    /**
     * 确认下单
     */
    private void placeOrder(int count, int periodId) {
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("periodId", String.valueOf(periodId));
        map.put("buyNum", String.valueOf(count));
        LKUtil.getHttpManager().postBody(HttpConstant.SNATCH_GOODS, map, getSnatchPeriodHander);
    }

    /**
     * 订单支付
     *
     * @param orderNo 订单号
     */
    private void payOrder(String orderNo) {
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("orderNo", orderNo);
        LKUtil.getHttpManager().postBody(HttpConstant.PAY_ORDER, map, pauOrderHandler);
    }

    @SuppressLint("HandlerLeak")
    private BaseHttpAsycResponceHandler pauOrderHandler = new BaseHttpAsycResponceHandler<Object>() {
        @Override
        public void onSuccess(Object o) {
            super.onSuccess(o);
            popupWindow.dismiss();
            //去详情页面
            String h5Url = HttpConstant.ORDER_H5_URL + "?appType=android" + "&orderNo=" + mOrderNo + "&ordersource=1";
            List<ParamUtils.NameValue> parList = ParamUtils.build()
                    .put(WebActivity.TITLE, "订单详情")
                    .put(WebActivity.URL, h5Url)
                    .put(WebActivity.ORDERNO, mOrderNo)
                    .put(WebActivity.PERIODID, snatchData.getPeriodId())
                    .create();
            IntentUtils.startAty(SnatchDetailsActivty.this, WebActivity.class, parList);
            SnatchDetailsActivty.this.finish();
        }

        @Override
        public void onFailed(int code, String message) {
            super.onFailed(code, message);
            showFailureDialog(message, null, "确定");
        }

        @Override
        public void onError() {
            super.onError();

        }
    };

    /**
     * 下单成功后返回数据
     */
    @SuppressLint("HandlerLeak")
    private BaseHttpAsycResponceHandler getSnatchPeriodHander =
            new BaseHttpAsycResponceHandler<String>() {
                @Override
                public void onSuccess(String orderNo) {
                    super.onSuccess(orderNo);
                    mOrderNo = orderNo;
                    if (mOrderNo != null) {
                        showInfoConfirmDialog(chooseCount, chooseExpend);
                    }
                }

                @Override
                public void onFailed(int code, String message) {
                    super.onFailed(code, message);
                    showFailureDialog(message, null, "确定");
                }

                @Override
                public void onError() {
                    super.onError();

                }
            };

    /**
     * webview加载进度
     *
     * @param newProgress
     */
    private void setNewProgress(int newProgress) {
        tv_snatch_details_btn.setVisibility(View.GONE);
        if (newProgress == MAX_PROGESS) {
            hideProgressBar();
            btbv_snatch_details.setRightBtnImageShow(true);
            tv_snatch_details_btn.setVisibility(View.VISIBLE);
            return;
        }
        if (progressBar.getVisibility() == View.GONE) {
            progressBar.setVisibility(View.VISIBLE);
        }
        progressBar.setMax(MAX_PROGESS);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            progressBar.setProgress(newProgress, true);
        } else {
            progressBar.setProgress(newProgress);
        }
    }

    /**
     * 隐藏进度条
     */
    private void hideProgressBar() {
        progressBar.setVisibility(View.GONE);
        ref_layout.setEnableRefresh(true);
    }

    /**
     * 设置底部按钮状态
     */
    private void setBottomBtnStatus(int status) {
        switch (status) {
            case 10:
                tv_snatch_details_btn.setText("即将开始");
                break;
            case 20:
                if (ShareUtils.getShareStatus(this, snatchData.getGoodsId())) {
                    tv_snatch_details_btn.setText("立即抢购");
                } else {
                    tv_snatch_details_btn.setText("分享后抢购");
                }
                break;
            case 30:
                tv_snatch_details_btn.setText("等待开奖");
                break;
            default:
                tv_snatch_details_btn.setText("已结束");
                tv_snatch_details_btn.setBackgroundColor(Color.parseColor("#CCCCCC"));
                break;
        }
    }

}
